package dk.rhok.server;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import dk.rhok.json.CoordinateCreator;
import dk.rhok.json.DangerZoneInstanceCreator;
import dk.rhok.model.Coordinate;
import dk.rhok.model.DangerZone;
import dk.rhok.model.DangerZoneImpl;
import dk.rhok.model.MapOverlay;
import dk.rhok.model.ShelterAssessmentImpl;
import dk.rhok.model.WatSanAssessmentImpl;

public class MapOverlayCreatorImpl implements MapOverlayCreator {

	@Override
	public MapOverlay addMapOverlayFromPOST(HttpServletRequest request) {

		String type;
		double latitude, longitude;

		try {
			latitude = Double.parseDouble(request.getParameter("latitude"));
			longitude = Double.parseDouble(request.getParameter("longitude"));
			type = request.getParameter("type");
		} catch (Exception e) {
			// TODO: Throw a nice exception
			return null;
		}

		// Switch the different types
		if (type.equals("shelter")) {
			// Get type specific data
			int households, people, dead, tents, jerryCans, kitchenSet, hygineKit;
			try {
				households = Integer.parseInt(request
						.getParameter("households"));
				people = Integer.parseInt(request.getParameter("people"));
				dead = Integer.parseInt(request.getParameter("dead"));
				tents = Integer.parseInt(request.getParameter("tents"));
				jerryCans = Integer.parseInt(request.getParameter("jerryCans"));
				kitchenSet = Integer.parseInt(request
						.getParameter("kitchenSet"));
				hygineKit = Integer.parseInt(request.getParameter("hygineKit"));
			} catch (Exception e) {
				// TODO: Throw a nice exception
				return null;
			}

			return new ShelterAssessmentImpl(new Date().getTime(), latitude,
					longitude, households, people, dead, tents, jerryCans,
					kitchenSet, hygineKit);
		} else if (type.equals("water")) {
			// Get type specific data
			String landowner, status;
			int yearInstalled;
			float depth;
			try {
				landowner = request.getParameter("landowner");
				status = request.getParameter("status");
				yearInstalled = Integer.parseInt(request
						.getParameter("yearsInstalled"));
				depth = Float.parseFloat(request.getParameter("depth"));
			} catch (Exception e) {
				// TODO: Throw a nice exception
				return null;
			}

			return new WatSanAssessmentImpl(new Date().getTime(), latitude,
					longitude, landowner, yearInstalled, status, depth);
		} else if (type.equals("danger_zone")) {
			// Danger zones are submitted in json format
			GsonBuilder json = new GsonBuilder();
			json.registerTypeAdapter(DangerZoneImpl.class, new DangerZoneInstanceCreator());
			json.registerTypeAdapter(Coordinate.class, new CoordinateCreator());
			Gson gson = json.create();
			
			DangerZone zone = gson.fromJson(request.getParameter("coordinates").trim(), DangerZoneImpl.class);
			
			return zone;
		}
		return null;
	}
}
